<template>
  <ea-dialog
    v-bind="$attrs"
    v-on="$listeners"
    width="800px"
    ref="elDialog"
    :title="title"
    :type="type"
    @submit="submit"
    @reset="handleReset"
    class="dialog"
    @closed="onClosed"
  >
    <el-scrollbar wrap-class="scroll-wrap-y">
      <el-form
        ref="form"
        :class="type === 'view' ? 'no-click' : ''"
        :rules="rules"
        :model="singleData"
        label-width="100px"
      >
        <el-form-item label="题型" prop="qustypeid">
          <el-select
            v-model="singleData.qustypeid"
            @change="singleData.answer = []"
            @focus="backsupOptions(singleData)"
            placeholder="请选择一个题型"
          >
            <el-option
              v-for="item in queType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科目" prop="subid">
          <el-select
            placeholder="请选择科目"
            @change="onSubChange"
            clearable
            v-model="singleData.subid"
          >
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节" prop="chapterid">
          <el-select
            placeholder="请选择章节"
            clearable
            v-model="singleData.chapterid"
          >
            <el-option
              v-for="item in chapters"
              :key="item.chapterid"
              :label="item.chaptername"
              :value="item.chapterid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题干" prop="quetitle">
          <el-input
            type="textarea"
            show-word-limit
            autosize
            :maxlength="200"
            placeholder="请输入题干"
            v-model="singleData.quetitle"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="难度" prop="difficult">
          <el-select
            v-model="singleData.difficult"
            placeholder="请选择题目难度"
          >
            <el-option label="简单" value="1" />
            <el-option label="一般" value="2" />
            <el-option label="困难" value="3" />
          </el-select>
        </el-form-item>
        <template v-if="singleData.qustypeid !== 1002">
          <!-- the discussion questions have no options-->
          <template v-for="(option, index) in singleData.queoptions">
            <!--the judgement questions have only two options-->
            <el-form-item
              v-if="singleData.qustypeid !== 3 || index < 2"
              :key="'op' + index"
            >
              <template v-slot:label>
                <component
                  :label="option.optionstr"
                  v-model="singleData.answer"
                  :disabled="!option.optioncontent.length"
                  v-bind:is="
                    /[1|3]/.test(singleData.qustypeid)
                      ? 'el-radio'
                      : 'el-checkbox'
                  "
                />
              </template>
              <el-input
                show-word-limit
                :maxlength="100"
                :disabled="singleData.qustypeid === 3"
                placeholder="请输入选项"
                v-model="option.optioncontent"
              >
              </el-input>
            </el-form-item>
          </template>
        </template>
        <el-form-item label="解析" prop="queanalysis">
          <el-input
            type="textarea"
            autosize
            show-word-limit
            :maxlength="400"
            placeholder="请输入题目解析"
            v-model="singleData.queanalysis"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="知识点" prop="queanalysis">
          <el-input
                  autosize
                  show-word-limit
                  :maxlength="100"
                  placeholder="请输入知识点"
                  v-model="singleData.knowledgePoint"
          >
          </el-input>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </ea-dialog>
</template>

<script>
import editAndAdd from "../../../mixins/business/editAndAdd";
import { queType } from "../../../staticData/queType";

const MAX_OPTION_NUMBER = 6;

export default {
  name: "EaQue",
  mixins: [editAndAdd],
  props: ["subjects"],
  data() {
    return {
      moduleName: "题目",
      singleData: {
        answer: [],
        difficult: "1",
        chapterid: null,
        queanalysis: "",
        queid: null,
        queoptions: [],
        quetitle: "",
        qustypeid: 1,
        subid: null
      },
      backsupQueoptions:[],
      autoIncreaseFlag:0,
      questionType:0,
      answer:[],
      rules: {
        subid: { required: true, message: "请选择科目！" },
        chapterid: { required: true, message: "请选择章节！" },
        quetitle: { required: true, message: "请输入题干！" },
        difficult: { required: true, message: "请选择题目难度！" }
      },
      queType,
      chapters: []
    };
  },
  watch: {
    type: {
      immediate: true,
      handler(n) {
        this.initOptions(n);
      }
    },
    "singleData.qustypeid"(n) {
      if (/'view'|'edit'/.test(this.type)) return;
      this.initOptions(n);
      if (n === 3) {
        this.$nextTick(() => {
          this.singleData.queoptions[0].optioncontent = "正确";
          this.singleData.queoptions[1].optioncontent = "错误";
        });
      }
    }
  },
  methods: {
    onSubChange(subid) {
      this.chapters.splice(0);
      this.singleData.chapterid = null;
      subid && this.api.getChapter.apply(this, [subid]);
    },
    onClosed() {
      this.singleData = {answer:[],difficult:"1",chapterid:null,queanalysis:"",queid:null,queoptions:[],quetitle:"",qustypeid:1,subid:null},
      this.initOptions();
      this.end();
      this.backsupQueoptions=[]
      this.answer=[]
      this.questionType=0
      this.autoIncreaseFlag=0
    },
    backsupOptions(n){
      if(this.autoIncreaseFlag==0){
        this.singleData.queoptions.forEach((item)=>{
          this.backsupQueoptions.push(item)
        })
        this.answer=this.singleData.answer
        this.questionType=this.singleData.qustypeid
        this.autoIncreaseFlag=1
      }
    },
    initOptions(n) {
      if('edit'==n){//再点击编辑时选择追加至F
        this.$nextTick(() => {
          for (let i = this.singleData.queoptions.length; i < MAX_OPTION_NUMBER; i++)
            this.singleData.queoptions.push({
              optioncontent: "",
              optionid: null,
              optionstr: String.fromCharCode(65 + i)
            });
        });
      }else if((this.questionType!=n && this.questionType!=0) || (undefined==n && this.questionType==0) || ('add'==n)){//切换至其他题目类型时
        this.singleData.queoptions.splice(0);
        for (let i = 0; i < MAX_OPTION_NUMBER; i++)
          this.singleData.queoptions.push({
            optioncontent: "",
            optionid: null,
            optionstr: String.fromCharCode(65 + i)
          });
      }else if(this.questionType==n){//在编辑页面从其他题目类型切换回当前题目类型时
        this.singleData.queoptions=[]
        this.backsupQueoptions.forEach((item)=>{
          this.singleData.queoptions.push(item)
        })
        this.singleData.answer=this.answer
        for (let i = this.backsupQueoptions.length; i < MAX_OPTION_NUMBER; i++)
          this.singleData.queoptions.push({
            optioncontent: "",
            optionid: null,
            optionstr: String.fromCharCode(65 + i)
          });
      }
    },
    handle() {
      const copySingleData = this.deepClone(this.singleData);
      let { queoptions, answer, qustypeid } = copySingleData;

      if (qustypeid === 3 && copySingleData.queoptions.length > 2)
        copySingleData.queoptions.splice(2, queoptions.length - 2);

      copySingleData.queoptions = queoptions.filter(
        option => option.optioncontent
      );

      Array.isArray(answer) && (copySingleData.answer = answer.join(""));

      if (!answer.length) {
        this.$message.error("请在选项前选择题目答案!");
        return Promise.reject();
      }
      //选项不连续判断 例如:ABD
      for (let i = 0; i < copySingleData.queoptions.length - 1; i++) {
        const option = copySingleData.queoptions[i].optionstr.charCodeAt();
        const nextOption = copySingleData.queoptions[
          i + 1
        ].optionstr.charCodeAt();
        if (nextOption - option > 1) {
          this.$message.error("输入的选项不连续!!");
          return Promise.reject();
        }
      }
      if (
        (qustypeid === 3 && copySingleData.queoptions.length < 2) ||
        (copySingleData.queoptions.length < 4 && qustypeid !== 3)
      ) {
        this.$message.error("判断题选项为2个,单选,多选选项至少为4个");
        return Promise.reject();
      }
      return this.axios.post("/sys/question/addOrUpdateQue", copySingleData);
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.initOptions();
    }
  }
};
</script>

<style scoped>
.dialog >>> .el-textarea__inner {
  min-height: 66px !important;
}
</style>
